<?php declare(strict_types=1);

namespace App\Http\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Swoft\Bean\Annotation\Mapping\Bean;
use Swoft\Http\Server\Contract\MiddlewareInterface;
use App\Model\SystemUser;

/**
 * 总后台登录token验证-中间件
 * @Bean()
 */
class AdminLoginMiddleware implements MiddlewareInterface
{
        /**
         * Process an incoming server request.
         *
         * @param ServerRequestInterface $request
         * @param RequestHandlerInterface $handler
         *
         * @return ResponseInterface
         * @inheritdoc
         */
        public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
        {
                $strToken = str_replace('Bearer ', '', $request->getHeader('authorization')[0]);
                if (!$strToken) return response()->withStatus(403)->withContent('Headers Bearer can not be empty!');
                $arrTokenData = json_decode(decryptOpenssl($strToken, SSL_KEY, SSL_IV), true);
                if (!$arrTokenData) return response()->withStatus(403)->withContent('Bearer validation fails!');
                $strUserId = $arrTokenData['userId'];
                $arrField = ['userId', 'updateTime'];
                $arrUser = SystemUser::primaryKeyFind($strUserId, $arrField);
                if (!$arrUser) return response()->withStatus(403)->withContent('Bearer validation fails!');
                if ($arrUser['updateTime'] != $arrTokenData['updateTime']) return response()->withStatus(403)->withContent('The account information has been changed. Please log in again!');
                $request->userId = $strUserId;
                $response = $handler->handle($request);
                return $response;
        }
}